# from google.appengine.api import rdbms
from operator import itemgetter
import urllib2
import urllib
import json

# conn = rdbms.connect(instance="nickstorelocator:nickdbprod", database="nickstorelocator")
# cursor = conn.cursor()
# cursor.execute("SELECT * FROM markers")
# rawData = cursor.fetchall()
# conn.close()

rawData = [(1, u"Amici's East Coast Pizzeria", u'790 Castro St, Mountain View, CA', 37.387138, -122.08324), 
(2, u'Frankie Johnnie & Luigo Too', u'939 W El Camino Real, Mountain View, CA', 37.386336999999997, -122.08582), 
(3, u"Kapp's Pizza Bar & Grill", u'191 Castro St, Mountain View, CA', 37.393886999999999, -122.07892), 
(4, u'Round Table Pizza: Mountain View', u'570 N Shoreline Blvd, Mountain View, CA', 37.402653000000001, -122.07935000000001), 
(5, u"Tony & Alba's Pizza & Pasta", u'619 Escuela Ave, Mountain View, CA', 37.394011999999996, -122.09553)]


def callGoogleApi(api, params):

	if api == "geocode":
		apiUrl = "/maps/api/geocode/json"
	elif api == "distance":
		apiUrl = "/maps/api/distancematrix/json"
	else:
		return "api url not given"

	encodedParams = urllib.urlencode(params)
	url = "http://maps.googleapis.com%s?%s" % (apiUrl, encodedParams)
	response = urllib2.urlopen(url)
	rawJson = response.read()
	encodedJson = json.loads(rawJson)

	# http://maps.googleapis.com/maps/api/geocode/json?address=16+rhonda+ave+willetton&sensor=false
	# http://maps.googleapis.com/maps/api/distancematrix/json?origins=25+rhonda+ave+willetton&destinations=Rossmoyne&senor=false
	return encodedJson


def index():

	return dict(rawData=rawData)


def getNearestStore():

	try:
		storeData = []
		origin = request.vars.userAddressInput

		for store in rawData:
			name = store[1]
			address = store[2]
			lat = store[3]
			lng = store[4]

			destData = callGoogleApi("distance", {"origins": origin, "destinations": store[2],"sensor": "false"})

			if destData["status"] == "OK":
				distanceValue = destData["rows"][0]["elements"][0]["distance"]["value"]
				distanceText = destData["rows"][0]["elements"][0]["distance"]["text"]
				storeData.append((name,address,lat,lng,distanceValue,distanceText))
			else:
				pass
			
		if len(storeData) == 0:
			storeData = "null"
		else:
			storeData = sorted(storeData, key=itemgetter(4))

		error = "no error"
		apistatus = "api is ok"

	except Exception, e:
		storeData = "null"
		error = e
		apistatus = callGoogleApi("distance", {"origins": "Google Headquarters, Amphitheatre Parkway, Mountain View, CA", "destinations": '191 Castro St, Mountain View, CA',"sensor": "false"})

	return dict(storeData=storeData, error=error, apistatus=apistatus)